By
木子雷
阅读数: 次
前言:
Java实现 “DESede” 对称加密;
前提:
在代码运行前,需要提前将一个依赖导入到项目中 pom.xml 中,使用这个依赖中的base64进行编解码;
1 2 3 4 5 6
| <!-- base64编码使用 --> <dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> <version>1.12</version> </dependency>
|
代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
| import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import org.apache.commons.codec.binary.Base64; public class DESedeUtil {
private static final String KEY_ALGORITHM = "DESede";
private static final String CIPHER_ALGORITHM = "DESede/ECB/PKCS5Padding";
public static String generateKey() throws Exception { KeyGenerator kg = KeyGenerator.getInstance(KEY_ALGORITHM); kg.init(168); SecretKey secretKey = kg.generateKey(); return Base64.encodeBase64String(secretKey.getEncoded()); }
public static String encrypt(String source, String key) throws Exception { byte[] sourceBytes = source.getBytes("UTF-8"); byte[] keyBytes = Base64.decodeBase64(key); Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM); cipher.init(Cipher.ENCRYPT_MODE,new SecretKeySpec(keyBytes, KEY_ALGORITHM)); byte[] decrypted = cipher.doFinal(sourceBytes); return Base64.encodeBase64String(decrypted); }
public static String decrypt(String encryptStr, String key) throws Exception { byte[] sourceBytes = Base64.decodeBase64(encryptStr); byte[] keyBytes = Base64.decodeBase64(key); Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM); cipher.init(Cipher.DECRYPT_MODE,new SecretKeySpec(keyBytes, KEY_ALGORITHM)); byte[] decoded = cipher.doFinal(sourceBytes); return new String(decoded, "UTF-8"); } public static void main(String[] args) { try { String key = generateKey(); System.out.println("秘钥:"+key); String encryptStr = encrypt("hello", key); System.out.println("密文:"+ encryptStr); String resource = decrypt(encryptStr, key); System.out.println("明文:"+ resource); System.out.println("校验:"+ "hello".equals(resource)); } catch (Exception e) { e.printStackTrace(); } } }
|